//
//  DiscussDetailViewController.m
//  OperationPro
//
//  Created by Mac on 16/10/9.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "DiscussDetailViewController.h"
#import "DiscussDetailView.h"
#import "DiscussDetailModel.h"
#import "CSendToolView.h"
#import "CQiniuFileUpload.h"
#import "QNUploadOption.h"
#import "CFileUpload.h"
#import "UIImage+ResizeMagick.h"
#import "DiscussNewDetailViewController.h"
#import "ImagesShowViewController.h"
@interface DiscussDetailViewController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    UIImage *_newIamge;
    BOOL isNewImg;
    NSMutableArray *_photosAr;

}
@property (nonatomic, strong) DiscussDetailView *mainView;
@property (nonatomic, strong) CSendToolView *toolView;
@end

@implementation DiscussDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)initView{
    [super initView];

    _photosAr=[[NSMutableArray alloc]init];
    [self setTitle:@"讨论贴"];
  
    DiscussDetailView *mainView = [[DiscussDetailView alloc]initWithFrame:CGRectZero withdataModel:self.invitationModel  withImageString:self.imageString withDescribe:self.describe  withIsWarnuiud:self.isWarnuiud withWarnuiud:self.warnuiud];
    mainView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:mainView];
    [mainView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view);
        make.bottom.equalTo(self.view).mas_offset(-40);
        make.top.equalTo(self.view).mas_offset(71);
    }];
    _mainView = mainView;
    [mainView setCCellSelect:^(DiscussDetailModel *data) {
//        [_toolView setReplyName:data.D_author];
        if (data.D_author==nil) {
            
        }else
        {
            [_toolView setReplyInfo:@{@"name":data.D_author, @"lever":data.D_uuid}];
            [_toolView becomeFirstResponder];
        }
       
    }];
    [mainView setDiscussDetailBecomeFirstResponse:^{
        [_toolView resignFirstResponder];
    }];
    
    //进入报修详情
    [mainView setGotoDetail:^(NSString *warnuiud1) {
        DiscussNewDetailViewController *discussVC=[[DiscussNewDetailViewController alloc]init];
        discussVC.warningUuid=warnuiud1;
        [self pushController:discussVC];
    }];

    
    
    CSendToolView *toolView = [[CSendToolView alloc] initWithFrame:CGRectMake(0, WindowHeight - 40, WindowWidth, 40)];
    [self.view addSubview:toolView];
    _toolView = toolView;
    
    [toolView setSendAction:^(NSString * reply) {
        self.toolView.isImage=NO;
        NSString *pre = [NSString stringWithFormat:@"回复 %@：", _toolView.replyInfo[@"name"]];
      //换行符的处理
        NSString *sendStr=[reply stringByReplacingOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [reply length])];
        if (([sendStr isEqualToString:@""]||[[reply stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]length]==0)&&isNewImg==NO) {
            [CClass showMessage:@"请输入回复内容！"];
            return ;
        }
        
        
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:self.invitationModel.I_uuid forKey:@"uuid"];
        
        if (![reply hasPrefix:pre]) {
//            [dic setObject:@"0" forKey:@"refer_uuid"];

        }else{
           
            reply = [reply substringWithRange:NSMakeRange(pre.length, reply.length - pre.length)];
            [dic setObject:_toolView.replyInfo[@"lever"] forKey:@"refer_uuid"];

        }


        NSString *sendString=[reply stringByReplacingOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [reply length])];
        
       
        if (([sendString isEqualToString:@""]||[[reply stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]length]==0)&&isNewImg==NO) {
            [CClass showMessage:@"请输入回复内容！"];
            return ;
        }
        [dic setObject:reply forKey:@"content"];
        [_toolView setReplyInfo:@{@"name":@"", @"lever":@""}];
        NSMutableArray *ar=[[NSMutableArray alloc]init];
        if (isNewImg==NO) {
            [dic setObject:@"" forKey:@"image"];
            //上传图片
            [self setIsLoading:YES];
            [CClass HttpRequestTask:NO withUrl:@"discuss_reply" withData:dic notifyError:YES onSuccess:^(BaseModel *model) {
                [self setIsLoading:NO];
                [_mainView refresh];
            } onError:^(BaseModel *model) {
                [self setIsLoading:NO];
 
            }];
        }else
        {
            //新图片
            NSString *imgName = [NSString stringWithFormat:@"%@_%@.jpg", [Common getDateTimeString], [Common randomStringWithLength:8]];
            NSData *data =[_newIamge resizedAndReturnData];
            [ar addObject:[CFileModel initWithFile:data name:imgName]];
            [dic setObject:imgName forKey:@"image"];
            [self setIsLoading:YES];

            [[CQiniuFileUpload uploadFile] uploadFiles:ar progress:^(CFileUpload *upload, float per) {
                
            } finish:^(CFileUpload *upload, NSArray *models, NSError *error) {
                if (ar.count>0) {
                    
                    [CClass HttpRequestTask:NO withUrl:@"discuss_reply" withData:dic notifyError:YES onSuccess:^(BaseModel *model) {
                        [_mainView refresh];
                        self.toolView.isImage=NO;
                        isNewImg=NO;
                        [self setIsLoading:NO];

                    } onError:^(BaseModel *model) {
                        [self setIsLoading:NO];

                    }];
                    
                }
            }];

        }
       
    }];
    
    [toolView setChangeFrame:^(CGRect frame) {
        
    }];
    
    [toolView setBtnAction:^{
        if (isNewImg==NO) {
            [self chooseClick];

        }else if (isNewImg==YES){
            //放大图片
            ImagesShowViewController *imageVC=[[ImagesShowViewController alloc]init];
            imageVC.name=@"讨论贴";
            imageVC.images=_photosAr;
            imageVC.canDel=YES;
            [imageVC.navBar setBackAction:^{
           
                [self.navigationController dismissViewControllerAnimated:YES completion:^{
                    
                }];

             }];
            [imageVC setFinishDelBlock:^(NSInteger j) {
                isNewImg=NO;
                [_photosAr removeAllObjects];
                [self.navigationController dismissViewControllerAnimated:YES completion:^{
                    
                }];
                self.toolView.isImage=NO;

            }];
        
            [self.navigationController presentViewController:imageVC animated:YES completion:nil];
  }
    }];
    [_toolView setReplyInfo:@{@"name":@"", @"lever":@""}];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [_toolView viewWillAppear];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [_toolView viewWillDisAppear];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//打开系统相册
#pragma mark -- 打开系统相册
-(void)chooseClick{
    UIActionSheet *sheet;
    
    //判断是否支持相机
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        
        sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self
                                   cancelButtonTitle:@"取消"
                              destructiveButtonTitle:nil
                                   otherButtonTitles:@"拍照", @"从相册中选取", nil];
    }else{
        sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self
                                   cancelButtonTitle:@"取消"
                              destructiveButtonTitle:nil
                                   otherButtonTitles:@"从相册中选取", nil];
    }
    sheet.actionSheetStyle=UIActionSheetStyleBlackOpaque;
    sheet.tag = 200;
    [sheet showInView:self.view];
}

#pragma mark -- 判断是否支持相机 ，跳转到相机 或相册界面
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (actionSheet.tag == 200){
        NSInteger sourceType = 0;
        //判断是否支持相机
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            switch (buttonIndex){
                case 0:
                    //相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                case 1:
                    //相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
                case 2:
                    //取消
                    return;
                    break;
                default:
                    break;
            }
        }else{
            if (buttonIndex == 0){
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }else if(buttonIndex==1){
                return;
            }
        }
        
        //跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc]init];
        imagePickerController.delegate = self;
        imagePickerController.sourceType = sourceType;
        imagePickerController.allowsEditing = NO;
        //状态栏变成白色
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    [navigationController.navigationBar setBackgroundColor:[UIColor whiteColor]];
    [navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
    navigationController.navigationBar.translucent = NO;
    [[UIApplication  sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    [[UIApplication  sharedApplication]  setStatusBarHidden:NO];
}

#pragma mark -- UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        picker.allowsEditing=YES;
        // _headImg.image = image;
        //设置image的尺寸
        //初始化imageNew为从相机中获得的--
        UIImage *imageNew = [info objectForKey:UIImagePickerControllerOriginalImage];
        NSData *imageData=  [CClass compressImageQuality:imageNew];
        _newIamge=[UIImage imageWithData:imageData];
        [_photosAr removeAllObjects];
        [_photosAr addObject:imageNew];

        isNewImg=YES;
        self.toolView.isImage=YES;

        [self dismissViewControllerAnimated:YES completion:nil];
    });
}


-(void) imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:^{}];
}

@end
